package a07_二叉树;

/**
 * <p>
 * a26_二叉树的最近公共祖先
 * </p>
 *
 * 要从下往上遍历
 *
 * 采用回溯，必须使用左右中
 *
 *
 *
 *
 *
 * @author flyduck
 * @since 2024/12/24
 */
public class a26_二叉树的最近公共祖先 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }

        if (root == p || root == q) {
            return root;
        }

        TreeNode leftNode = lowestCommonAncestor(root.left, p, q);
        TreeNode rightNode = lowestCommonAncestor(root.right, p, q);
        if (leftNode != null && rightNode != null) {
            return root;
        }else if(leftNode == null && rightNode != null){
            return rightNode;
        }else if(leftNode != null && rightNode == null){
            return leftNode;
        }else {
            return null;
        }
    }

}
